package com.edroid.droidhelper.bootloader;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

import com.edroid.droidhelper.pm.PluginLoader;
import com.edroid.droidhelper.pm.PluginLoader.PluginLoadCallback;
import com.edroid.droidhelper.pm.bean.PluginLoadResults;


/**
 * 加载插件入口类，通过 config.properties 配置插件信息
 * 
 * @author yichou 2015-1-15
 *
 */
public class BootLoader {
	static String pluginName = null;
	static String pluginEntryClass = null;
	static String pluginEntryMethod = null;
	
	
	public static void main(String[] args) {
		InputStream is = null;
		try {
			is = BootLoader.class.getResourceAsStream("/config.properties");
			Properties properties = new Properties();
			properties.load(is);
			
			pluginName = properties.getProperty("plugin_name");
			pluginEntryClass = properties.getProperty("plugin_entry_class");
			pluginEntryMethod = properties.getProperty("plugin_entry_method");
		} catch (Exception e) {
			e.printStackTrace();
			
			throw new RuntimeException("read config fail! " + e.getMessage());
		} finally {
			try {
				is.close();
			} catch (Exception e2) {
			}
		}
		
		if(pluginName == null)
			throw new NullPointerException("plugin name not configed!");
		if(pluginEntryClass == null)
			throw new NullPointerException("plugin entry class not configed!");
		if(pluginEntryMethod == null)
			throw new NullPointerException("plugin entry method not configed!");
		
		PluginLoader.load(pluginName, PluginLoader.LOADE_MODE_LOCAL_FIRST, new PluginLoadCallback() {

			@Override
			public void onExist(int curVer, String plgPath) {
			}

			@Override
			public void onUpdateVer(int oldVer, int newVer, String plgPath) {
			}

			@Override
			public void onLoadSuccess(PluginLoadResults ret) {
				try {
					Class<?> cls = ret.classLoader.loadClass(pluginEntryClass);
					Method method = cls.getDeclaredMethod(pluginEntryMethod, String[].class);
					method.invoke(null, (Object) new String[] { "a" });
				} catch (Exception e) {
					e.printStackTrace();
					
					throw new RuntimeException("start plugin fail! " + e.getMessage());
				}
			}

			@Override
			public void onFailure(int code, String msg, Exception e) {
				System.out.println("error code=" + code + " msg=" + msg);
				if(e != null)
					e.printStackTrace();
			}
		});
	}
}
